<template>
  <div class="app-container assetDepreciation">
    <div v-show="!assetDetailInfo.visible" class="app-container-flex">
      <NewFullScreen
        v-model="showDialog"
        title="资产折旧"
        @returnBack="$emit('returnModify')"
        :needReturn="false"
      >
        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t("basic_information") }}</p>
          </div>
          <div class="model-panel-body">
            <!-- form -->
            <page-form
              class="paddingBox order-model-formBox flex_wrap_start_start"
              v-model:ref-obj="formInfo.ref"
              :disabled="formInfo.disabled"
              :data="formInfo.data"
              :field-list="formInfo.fieldList"
              :rules="formInfo.rules"
              :label-width="formInfo.labelWidth"
            >
              <template v-slot:form-fiscalPeriodName>
                {{ formInfo.data.fiscalPeriodName }}
              </template>
              <template v-slot:form-businessDate="scope">
              <el-date-picker
                v-model="formInfo.data['businessDate']"
                type="date"
                value-format="YYYY-MM-DD"
                :disabled-date="
                  (time) => {
                    let _time = formatDate(new Date(time), 'YYYY-MM-DD')
                    return _time > disEndDate || _time < disStartDate
                  }
                "
                :clearable="false"
              />
            </template>
            </page-form>
            <!-- <p style="color: red">
              &nbsp; &nbsp; &nbsp; &nbsp;
              &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;注意：
              运行资产折旧或摊销后，将生成本期折旧记录，且无法取消
            </p> -->
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')" />
          </div>
          <div class="model-panel-body">
            <!-- 条件栏 -->
            <page-filter :filter-list="filterInfo.list">
              <template v-slot:filter-depreciation>
                <el-button @click="depreciation(1)"> 折旧 </el-button>
              </template>
              <template v-slot:filter-depreciationRollup>
                <el-button @click="depreciation(2)"> 反折旧 </el-button>
              </template>
            </page-filter>
            <div class="flex_full_item">
              <table-container
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :api="tableInfo.api"
                :query="filterInfo.query"
                :check-box="false"
                :tab-index="true"
                :field-list="tableInfo.fieldList"
                :row-class-name="tableRowOtherClassName"
                @sortChange="sortChange"
                @handleEvent="handleEvent"
                @pageInfo="pageInfo"
              >
                <template v-slot:col-orderNo="scope">
                  <span class="slip-edit" @click="showDetail(scope.row)">{{
                    scope.row.assetName
                  }}</span>
                </template>
                <template v-slot:col-assetName="scope">
                  <span class="slip-edit" @click="showAssetDetail(scope.row)">{{
                    scope.row.assetName
                  }}</span>
                </template>
              </table-container>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <el-dialog
      class="progress"
      v-model="centerDialogVisible"
      width="100%"
      center
      :modal="false"
      :fullscreen="true"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div>
        <el-progress type="circle" :percentage="percentage" />
      </div>
    </el-dialog>
    <Select-asset
      v-if="selectAssetInfo.visible"
      :table-key="selectAssetInfo.tableKey"
      v-model:show-dialog="selectAssetInfo.visible"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      :check-box="true"
      @callback="callBackAsset"
    />
    <!-- 详情页 -->
    <asset-card-detail
      v-if="assetDetailInfo.visible"
      :id="assetDetailInfo.id"
      v-model:visible="assetDetailInfo.visible"
      :title="assetDetailInfo.title"
    />
  </div>
</template>
<script setup name="assetDepreciation">
import { getCustomizeSetting } from "@/api/customize";
import {
  saveAssetDepreciation,
  depreciationDoDepr,
  depreciationRollbackDepr,
} from "@/api/asset.js";
import { getCurrentFiscalPeriod, getDepotAll } from "@/api/core.js";
import {
  setDisableTime,
  _getCurrentFiscalPeriod,
} from '@/common/js/dateOperation'
import { formatDate } from '@/utils/index'
import { assetDepreciationCustomizeListPage } from "@/api/asset.js";
import moment from "moment";
// import XEUtils from 'xe-utils'
import ScanInputBox from "@/components/SelectAsset/ScanInputBox";
const AssetCardDetail = defineAsyncComponent(() =>
  import("@/views/asset/assetManage/assetCard/details")
);


const { proxy } = getCurrentInstance();
const emits = defineEmits();
const props = defineProps(["visible", "id"]);
const percentage = ref(0);
const interval = ref(null);
const centerDialogVisible = ref(false);
const systemConfig = ref(proxy.$store.state.permission.systemConfig);
const scanInfo = ref({
  query: {
    assetStatus: "1,3",
    assetSourceAuth: true,
  },
});
const formInfo = ref({
  disabled: false,
  ref: null,
  data: {
    fiscalPeriodId: "",
    fiscalPeriodName: "",
  },
  fieldList: [
    { label: "当前会计期间", value: "fiscalPeriodName", type: "slot" },
    {
      label: '业务日期',
      value: 'businessDate',
      type: 'slot',
      TimePickerOptions: {},
    },
  ],
  rules: {
    fiscalPeriodName: [
      {
        required: true,
        message: "请选择当前会计期间",
        trigger: "change",
      },
    ],
    businessDate: [
      {
        required: true,
        message: '请选择业务日期',
        trigger: 'change',
      },
    ],
  },
  labelWidth: "180px",
});
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      fiscalPeriodId: {
        queryType: "IN",
        queryCategory: "AND",
        value: "",
      },
    },
  },
  list: [
    {
      type: "slot",
      value: "depreciation",
    },
    {
      type: "slot",
      value: "depreciationRollup",
    },
  ],
});
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
});
const selectAssetInfo = ref({
  visible: false,
  tableKey:
    "addCoreAssetByDepreciation-com.slip.spd.entity.vo.core.CoreAssetVO",
  query: {
    queryParams: {
      postingDateFilter: true,
      netAmountZeroFilter: true,
      rollBackDeprFilter: true,
      afterFiscalPeriodDateFilter: true,
      availableMonth: true,
    },
    queryMap: {
      assetStatus: {
        queryType: "IN",
        queryCategory: "AND",
        value: "1,3",
      },
      assetSourceAuth: {
        asTbName: "core_asset,core_asset",
        columnName: "use_dept_id,depot_id",
        queryType: "IN",
        queryCategory: "AND",
        value: "assetSourceAuth",
      },
      id: {
        queryType: "NOT_IN",
        queryCategory: "AND",
        value: "",
      },
      status: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: 3,
      },
      isLocked: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: 0,
      },
    },
  },
});
const allAssetFilterInfo = ref({
  queryParams: {},
  queryMap: {},
  customizeUserVO: {},
});
const assetDetailInfo = ref({
  visible: false,
  id: "",
  title: "资产详情",
});

// 过滤相关配置
const groupSelectInfo = ref({
  options: [],
  selections: [],
  data: [],
});
const slipSelectRequest = ref(true);
const showDialog = ref(true);

// const showDialog = computed({
//   get() {
//     return props.visible;
//   },
//   set(newValue) {
//     emits("update:visible", newValue); // 更新父组件visible
//   },
// });
const canSave = computed(() => {
  return tableInfo.value.data.length;
});
const canRemoveProduct = computed(() => {
  console.log(tableInfo.value.selections);
  return tableInfo.value.selections.length;
});
let disStartDate = ref('')
let disEndDate = ref('')
onMounted(() => {
  proxy.$nextTick(() => {
    //获取当前会计期间
    
  });
});
const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
});
setData();
function setData() {
  let obj = {
    typeValue: {
      label: "类型",
      value: "typeValue",
      asValue: "type",
      componentType: "select-model",
      code: "asset_adjust_type",
      show: false,
      hidden: true,
    },
    //accountingPeriod: {
    //  label: "会计期间",
    //  value: "accountingPeriod",
    //  componentType: 'date',
    //  slot: true,
    //  show: false,
    //  hidden: true,
    //},
    statusValue: {
      label: "状态",
      value: "statusValue",
      asValue: "status",
      componentType: "select-model",
      code: "asset_adjust_order_status",
      show: false,
      hidden: true,
    },
    depotName: {
      label: "出库仓库",
      value: "depotName",
      asValue: "depotId",
      componentType: "slip-select",
      query: {
        depotAuth: "id",
        status: 1,
        useTypeId: "2",
      },
      api: getDepotAll,
      show: false,
      hidden: true,
    },
    fiscalPeriodName: {
      label: "会计期间",
      value: "fiscalPeriodName",
      asValue: "fiscalPeriodName",
      componentType: "select-fiscal-period",
      query: {
        fiscalType: 2,
      }, //1 = 物资 2 = 资产
      highlightRow: true,
      checkBox: false,
      show: false,
      hidden: true,
    },
  };
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  filterInfo.value.searchList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...proxy.$fn.deepClone(obj),
  });
  getCurrentFiscalPeriod(2).then((res) => {
      if (res && res.success) {
        formInfo.value.data.fiscalPeriodName = res.data.name;
        formInfo.value.data["fiscalPeriodId"] = res.data.id;
        filterInfo.value.query.queryMap.fiscalPeriodId.value = res.data.id
        
        disStartDate.value = res.data.startDate
        disEndDate.value = res.data.endDate

        let dateOperation = formatDate(new Date(), 'YYYY-MM-DD')
        if (dateOperation < res.data.startDate) {
          formInfo.value.data["businessDate"] = res.data.startDate
        }
        // 如果当前时间大于当前会计区间的开始时间，取当前会计区间的结束时间
        if (dateOperation > res.data.endDate) {
          formInfo.value.data["businessDate"] = res.data.endDate
        }
        getCustomize();
      }
    });
  
}

function pageInfo(obj) {
  page.value = obj;
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr);
    filterInfo.value.sortArr = arr;
    filterInfo.value.query.sortString = arr.length ? arr.toString() : "";
    getList();
  }
}
// 获取列表
async function getList() {
  tableInfo.value.refresh = Math.random();
}
function save() {
  formInfo.value.ref.validate((valid) => {
    if (valid) {
      let data = tableInfo.value.data;
      let assetIds = data.map((item) => item.id);
      let param = {
        ...formInfo.value.data,
        assetIds: assetIds,
      };
      saveAssetDepreciation(param).then((res) => {
        if (res && res.success) {
          // showDialog.value = false;
          emits("returnModify", false);
        }
      });
    }
  });
}

//展示明细
function showDetail(row) {
  // sessionStorage.setItem('storeRowId', row.id)
  // detailInfo.value.data = row
  // detailInfo.value.visible = true
}
function tableRowOtherClassName({ row }) {
  let rowId = sessionStorage.getItem("storeRowId");
  if (rowId && row.id === Number(rowId)) {
    return "check-row";
  }
  return "";
}
onUnmounted(() => {
  clearInterval(interval.value);
  interval.value = null;
});
function depreciation(isDepreciation) {
  if(!formInfo.value.data["businessDate"]) {
    proxy.$message.warning({
      message: '请选择业务日期！',
    })
    return
  }
  setProcess();
  const params = {
    fiscalPeriodId: formInfo.value.data["fiscalPeriodId"],
    businessDate: formInfo.value.data["businessDate"],
  };
  let api = isDepreciation == 1 ? depreciationDoDepr : depreciationRollbackDepr;
  api(params)
    .then((res) => {
      if (res && res.success) {
        percentage.value = 100;
        stopProcess();
        setTimeout(() => {
          getList();
        }, 1000);
      } else {
        stopProcess();
      }
    })
    .catch(() => {
      stopProcess();
    });
}

function stopProcess() {
  clearInterval(interval.value);
  interval.value = null;
  setTimeout(() => {
    centerDialogVisible.value = false;
    percentage.value = 0
  }, 1000);
}

function setProcess() {
  centerDialogVisible.value = true;
  interval.value = setInterval(() => {
    if (percentage.value >= 100) {
      percentage.value = 100;
      clearInterval(interval.value);
      interval.value = null;
      return;
    }
    let newPercentage = Number(Number(percentage.value + Math.random() * 3));
    percentage.value =
      newPercentage.toFixed(0) > 100 ? 100 : newPercentage.toFixed(0);
  }, 500);
}

function handleEvent(event, data) {
  console.log(data);
  tableInfo.value.selections = data;
}

function callBackAsset(data) {
  data.forEach((item) => {
    item.adjustBefore = item.originalAmount;
    item.assetVersion = item.version;
    item.assetId = item.id;
  });
  tableInfo.value.data = data.concat(tableInfo.value.data);
  getList();
}
function showAssetDetail(row) {
  assetDetailInfo.value.id = row.assetId;
  assetDetailInfo.value.visible = true;
}

function getCustomize(_slipSelectRequest = true) {
  let param = {
    tableKey:
      "assetAssetManageDepreciationList-com.slip.spd.entity.vo.asset.AssetDepreciationVO",
  };
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      filterInfo.value.query.customizeUserVO = data;
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      );
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      );
      tableInfo.value.fieldList = tableFieldInfo.fieldList;
      groupSelectInfo.value.options = tableFieldInfo.groupOption;
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      };
      filterInfo.value.searchList = searchInfo.searchList;
      filterInfo.value.searchList.forEach((item) => {
        // item.event = search
      });
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      );
      slipSelectRequest.value = _slipSelectRequest;
      tableInfo.value.api = assetDepreciationCustomizeListPage;
      getList();
    }
  });
}
</script>

<style lang="scss" scoped>
.assetDepreciation {
  :deep(.el-dialog) {
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(1, 1, 1, 0.2);
  }
  :deep(.el-progress__text) {
    color: #fff !important;
  }
}
</style>
